<template>
  <div class="ai-chat-page">
    <div class="chat-container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <input
          v-model="searchKeyword"
          placeholder="搜索对话记录..."
          class="search-input"
          @input="searchChats"
        />
        <button @click="clearSearch" class="clear-search-btn">清除</button>
      </div>
      
      <!-- 聊天历史区域 -->
      <div class="chat-history" ref="chatHistoryRef">
        <div v-for="chat in filteredChats" :key="chat.id" class="chat-item">
          <div class="chat-header">
            <span class="chat-time">{{ formatTime(chat.createdAt) }}</span>
            <button @click="deleteChat(chat.id)" class="delete-btn" title="删除对话">
              🗑️
            </button>
          </div>
          
          <div class="user-message">
            <div class="message-content">{{ chat.userInput }}</div>
          </div>
          <div class="ai-message">
            <div class="message-content">{{ chat.aiResponse }}</div>
          </div>
        </div>
        
        <!-- 当前对话 -->
        <div v-if="currentChat" class="chat-item current-chat">
          <div class="chat-header">
            <span class="chat-time">{{ formatTime(currentChat.createdAt) }}</span>
          </div>
          
          <div class="user-message">
            <div class="message-content">{{ currentChat.userInput }}</div>
          </div>
          <div class="ai-message">
            <div class="message-content">{{ currentChat.aiResponse }}</div>
            <div v-if="isLoading" class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!filteredChats.length && !currentChat && !isLoading" class="empty-state">
          <div class="empty-icon">🤖</div>
          <div class="empty-text">开始与AI助手对话吧！</div>
          <div class="empty-desc">AI会根据宝宝的日常记录为您提供专业建议</div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-container">
          <textarea
            v-model="userInput"
            placeholder="请输入您的问题..."
            class="input-field"
            rows="3"
            @keydown.enter.prevent="sendMessage"
            :disabled="isLoading"
          ></textarea>
          <button
            @click="sendMessage"
            :disabled="!userInput.trim() || isLoading"
            class="send-button"
          >
            {{ isLoading ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';

// 响应式数据
const chatHistory = ref([]);
const currentChat = ref(null);
const userInput = ref('');
const isLoading = ref(false);
const chatHistoryRef = ref(null);
const searchKeyword = ref('');
const filteredChats = ref([]);

// 发送消息
async function sendMessage() {
  if (!userInput.value.trim() || isLoading.value) return;
  
  const input = userInput.value.trim();
  userInput.value = '';
  isLoading.value = true;
  
  try {
    await startStreamingChat(input);
  } catch (error) {
    console.error('发送消息失败:', error);
    alert('发送失败，请重试');
  } finally {
    isLoading.value = false;
  }
}

// 流式AI对话
async function startStreamingChat(input) {
  const token = localStorage.getItem('auth_token');
  if (!token) {
    alert('请先登录');
    return;
  }

  // 创建当前对话对象
  currentChat.value = {
    userInput: input,
    aiResponse: '',
    createdAt: new Date().toISOString(),
    chatId: null
  };

  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/ai/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ userInput: input })
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6));
            if (data.content) {
              currentChat.value.aiResponse += data.content;
              currentChat.value.chatId = data.chatId;
            }
            if (data.isFinish) {
              // 对话完成，添加到历史记录
              chatHistory.value.unshift({ ...currentChat.value });
              currentChat.value = null;
              await loadChatHistory(); // 刷新历史记录
              return;
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', e);
          }
        }
      }
    }
  } catch (error) {
    console.error('流式对话失败:', error);
    throw error;
  }
}

// 格式化时间
function formatTime(timestamp) {
  return new Date(timestamp).toLocaleString();
}

// 加载对话历史
async function loadChatHistory() {
  const token = localStorage.getItem('auth_token');
  if (!token) return;

  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/ai/chat/history?page=0&size=20`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    const data = await response.json();
    chatHistory.value = data.chats || [];
    filteredChats.value = chatHistory.value;
    
    // 滚动到底部
    await nextTick();
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
    }
  } catch (error) {
    console.error('加载对话历史失败:', error);
  }
}

// 搜索对话
function searchChats() {
  if (!searchKeyword.value.trim()) {
    filteredChats.value = chatHistory.value;
    return;
  }
  
  filteredChats.value = chatHistory.value.filter(chat => 
    chat.userInput.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    chat.aiResponse.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
}

// 清除搜索
function clearSearch() {
  searchKeyword.value = '';
  filteredChats.value = chatHistory.value;
}

// 删除对话
async function deleteChat(chatId) {
  if (!confirm('确定要删除这条对话记录吗？')) return;
  
  const token = localStorage.getItem('auth_token');
  if (!token) return;

  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/ai/chat/${chatId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    // 从本地列表中移除
    chatHistory.value = chatHistory.value.filter(chat => chat.id !== chatId);
    filteredChats.value = filteredChats.value.filter(chat => chat.id !== chatId);
  } catch (error) {
    console.error('删除对话失败:', error);
    alert('删除失败，请重试');
  }
}

onMounted(() => {
  loadChatHistory();
});
</script>

<style scoped>
.ai-chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.search-input {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
}

.search-input:focus {
  outline: none;
  border-color: #007bff;
}

.clear-search-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
}

.clear-search-btn:hover {
  background-color: #5a6268;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
}

.chat-item {
  margin-bottom: 24px;
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chat-item.current-chat {
  border: 2px solid #007bff;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-time {
  font-size: 12px;
  color: #666;
}

.delete-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.delete-btn:hover {
  opacity: 1;
}

.user-message, .ai-message {
  margin-bottom: 12px;
}

.user-message {
  text-align: right;
}

.ai-message {
  text-align: left;
}

.message-content {
  display: inline-block;
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
}

.ai-message .message-content {
  background-color: #f1f3f4;
  color: #333;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  margin-top: 8px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #007bff;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  opacity: 0.8;
}

.chat-input {
  border-top: 1px solid #e0e0e0;
  padding: 20px 0;
  background: white;
  border-radius: 12px;
  margin-top: 20px;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  padding: 0 16px;
}

.input-field {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
}

.input-field:focus {
  outline: none;
  border-color: #007bff;
}

.send-button {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.send-button:hover:not(:disabled) {
  background-color: #0056b3;
}

.send-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
